#! /bin/sh
### BEGIN INIT INFO
# Provides:          radosgw
# Required-Start:    $remote_fs $named $network $time
# Required-Stop:     $remote_fs $named $network $time
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: radosgw RESTful rados gateway
# Description: radosgw RESTful rados gateway
### END INIT INFO

PATH=/sbin:/bin:/usr/bin

. /lib/lsb/init-functions

daemon_is_running() {
    daemon=$1
    if pidof $daemon >/dev/null; then
        echo "$daemon is running."
        exit 0
    else
        echo "$daemon is not running."
        exit 1
    fi
}

VERBOSE=0
for opt in $*; do
    if [ "$opt" = "-v" ] || [ "$opt" = "--verbose" ]; then
       VERBOSE=1
    fi
done

# prefix for radosgw instances in ceph.conf
PREFIX='client.radosgw.'

# user to run radosgw as (it not specified in ceph.conf)
DEFAULT_USER='www-data'

RADOSGW=`which radosgw`
if [ ! -x "$RADOSGW" ]; then
    [ $VERBOSE -eq 1 ] && echo "$RADOSGW could not start, it is not executable."
    exit 1
fi

case "$1" in
    start)
        for name in `ceph-conf --list-sections $PREFIX`;
        do
            auto_start=`ceph-conf -n $name 'auto start'`
            if [ "$auto_start" = "no" ] || [ "$auto_start" = "false" ] || [ "$auto_start" = "0" ]; then
                continue
            fi

            # is the socket defined?  if it's not, this instance shouldn't run as a daemon.
            rgw_socket=`$RADOSGW -n $name --show-config-value rgw_socket_path`
            if [ -z "$rgw_socket" ]; then
                continue
            fi

            # mapped to this host?
            host=`ceph-conf -n $name host`
            hostname=`hostname -s`
            if [ "$host" != "$hostname" ]; then
                [ $VERBOSE -eq 1 ] && echo "hostname $hostname could not be found in ceph.conf:[$name], not starting."
                continue
            fi

            user=`ceph-conf -n $name user`
            if [ -z "$user" ]; then
                user="$DEFAULT_USER"
            fi

            log_file=`$RADOSGW -n $name --show-config-value log_file`
            if [ -n "$log_file" ] && [ ! -e "$log_file" ]; then
                touch "$log_file"
                chown $user $log_file
            fi

            echo "Starting $name..."
            start-stop-daemon --start -u $user -x $RADOSGW -- -n $name
        done
        daemon_is_running $RADOSGW
        ;;
    reload)
        echo "Reloading $name..."
        start-stop-daemon --stop --signal HUP -x $RADOSGW --oknodo
        ;;
    restart|force-reload)
        $0 stop
        $0 start
        ;;
    stop)
        start-stop-daemon --stop -x $RADOSGW --oknodo
        ;;
    status)
        daemon_is_running $RADOSGW
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|force-reload|reload|status} [-v|--verbose]" >&2
        exit 3
        ;;
esac

